<?php

    /*
    * Находит в тексте и автоматически преобразует адреса, начинающиеся с ftp://, http://, https:// в активные ссылки.
    * $text = preg_replace("#(https?|ftp)://\S+[^\s.,>)\];'\&quot;!?]#", '<a href="\\0">\\0</a>', $text);
    */
    // Связь с сервисом Витакарты
    // require_once(dirname(__FILE__)."/../vcxml.php");
    
    // файл схемы для текущего сайта
    $mikron->Schema->Add(dirname(__FILE__)."/schema.xml", "Схема текущего сайта");

    $schedule_days = 8; // количество дней выводимых в расписании
    $datebegin = date('Y-m-d'); // дата начала вывода для расписания
    $dateend = date('Y-m-d', MikronDateTime::DateAdd("d", $schedule_days, strtotime($datebegin))); // дата последнего дня для расписания
    define('DATEBEGIN', $datebegin);
    define('DATEEND', $dateend);

    $dictionaries = new dictionaries_class();
    // $auth = new auth_class();

    // <login>
    /*
    function CreateLoginXML($slogin, $spassword)
    {
        $doc = new DOMDocument();
        $doc->formatOutput = true;
        $auth = $doc->createElement("authentification");
        //$text = $doc->createTextNode('Description');
        $auth->setAttribute('login', $slogin);
        $auth->setAttribute('password', $spassword);
        $doc->appendChild($auth);
        return $doc->SaveXML();
    }
    */

    // <getdictionaries>
    function CreateGetDictionariesXML($datebegin, $dateend)
    {
        $doc = new DOMDocument();
        $doc->formatOutput = true;
        $root = $doc->createElement("getdictionaries");
        $root->setAttribute('datebegin', $datebegin);
        $root->setAttribute('dateend', $dateend);
        $doc->appendChild($root);
        return $doc->SaveXML();
    }

    // <getposts>
    // расписание для специальностей, либо для конкретного работнега
    function CreateGetScheduleXML($need_for_speciality, $datebegin, $dateend, $need_for_posts = null)
    {
        $doc = new DOMDocument();
        $doc->formatOutput = true;
        $root = $doc->createElement("getschedule");
        $root->setAttribute('datebegin', $datebegin);
        $root->setAttribute('dateend', $dateend);
        if(is_array($need_for_posts))
        {
            foreach($need_for_posts as $post_code)
            {
                $post = $doc->createElement("post");   
                $post->setAttribute('code', $post_code);
                $root->appendChild($post);
            }
        }
        else
        {
            foreach($need_for_speciality as $speciality_code)
            {
                $speciality = $doc->createElement("speciality");   
                $speciality->setAttribute('code', $speciality_code);
                $root->appendChild($speciality);
            }
        }
        $doc->appendChild($root);
        // cut($doc->SaveXML());
        return $doc->SaveXML();
    }

    // класс-справочник
    class dictionaries_class
    {
        public $dic = Array();
        public function getdata($server)
        {
            global $auth;
            $xml = CreateGetDictionariesXML(constant('DATEBEGIN'), constant('DATEEND'));
            $buf = CallSoap('dictionaries', $xml, $server);
            $dom1 = new DomDocument();
            $dom1->loadXML($buf);
            $dictionaries_elm = $dom1->getElementsByTagName("dictionaries");
            $i = 0;
            foreach($dictionaries_elm as $dictionary_tag)
            {
                $dictionaries = $dictionary_tag->getElementsByTagName("dictionary");
                foreach($dictionaries as $dictionary)
                {
                    $for = $dictionary->getAttribute("for");
                    $elements = $dictionary->getElementsByTagName("element");
                    foreach($elements as $element)
                    {
                        $code = $element->getAttribute("code");
                        $value = $element->getAttribute("value");
                        $template = $element->getAttribute("template");
                        $value = iconv("UTF-8", "WINDOWS-1251", $value);
                        $template = iconv("UTF-8", "WINDOWS-1251", $template);
                        if($template!="")
                        {
                            $code .= ",$template";
                        }
                        $this->dic[$for][$code] = $value;
                    }
                }
            }
            return true;
        }
    }

    // SCHEDULE
    class ticket_class
    {
        public $id = null;
        public $time = null;
        public $status = null;
        function __construct($id, $time, $status)
        {
            $this->id = $id;
            $this->time = $time;
            $this->status = $status;
        }
    }

    class workdate_class
    {
        public $date = null;
        public $timebegin = null;
        public $timeend = null;
        public $place = null;
        public $tickets = Array();
        function __construct($date, $timebegin, $timeend, $place)
        {
            $this->date = $date;
            $this->timebegin = $timebegin;
            $this->timeend = $timeend;
            $this->place = $place;
        }
    }

    class post_class
    {
        public $id = null;
        public $fio = null;
        public $specialityname = null;
        public $spacialityid = null;
        public $state = null;
        public $division = null;
        public $workdates = Array();
    }

    class posts_class
    {

        public $posts_items = Array();

        /**
        * put your comment there...
        * 
        * @param Array of string $posts
        * @return posts_class
        */
        public function __construct($person, $lpu_guid, $specialities)
        {
            $datebegin = constant('DATEBEGIN');
            $dateend = constant('DATEEND');
            $workers = null;
            $buf = $this->getData($lpu_guid, $specialities, $datebegin, $dateend, $workers);
            $this->parsexml($buf);
        }

        public function getData($lpu_guid, $specialities, $datebegin, $dateend, $workers = null)
        {
            global $mikron;
            $dataObject = new DataObject('get_schedule');
            $dataObject->SetOADateTime('date_begin', $datebegin);
            $dataObject->SetOADateTime('date_end', $dateend);
            $dataObject->SetString('speciality', $specialities);
            $result = $mikron->Site->Soap->Call($lpu_guid, $dataObject);
           
                   /*
                        ob_clean();
            $mikron->Tools->cut($result);
            exit;
*/
            if($result instanceof DataObject)
            {
                $buf = $result->getString('schedule');
                $buf = str_replace('utf-16', 'utf-8', $buf);
                return $buf;
            }
        }

        public function items()
        {
            return $this->posts_items;
        }

        public function count()
        {
            return count($this->posts_items);
        }

        public function add($id, $fio, $profile, $specialityname, $spacialityid, $state, $division)
        {
            $post = new post_class();
            $post->id = $id;
            $post->fio = $fio;
            $post->profile = $profile;
            $post->specialityname = $specialityname;
            $post->spacialityid = $spacialityid;
            $post->state = $state;
            $post->division = $division;
            $this->posts_items[$specialityname][] = $post;
            return $post;
        }

        public function add_ticket($post_item, $id, $date, $time, $status, $place)
        {
            $ticket = new ticket_class();
            $ticket->id = $id;
            $ticket->date = $date;
            $ticket->time = $time;
            $ticket->status = $status;
            $ticket->place = $place;
            $post_item->tickets[] = $ticket;
        }

        public function parsexml($buf)
        {
            
            // конвертирование из cp1251 в Utf-8
            // cut($buf);
            // $buf = iconv("WINDOWS-1251", "UTF-8", $buf);
            $dom1 = new DomDocument();
            
            if(is_null($buf))
            {
                return;
            }

            $dom1->loadXML($buf);
            // cut($dom1->saveXML());
            $posts_elm = $dom1->getElementsByTagName("schedule");
            $i = 0;

            foreach($posts_elm as $posts_tag)
            {
                $posts = $posts_tag->getElementsByTagName("post");
                foreach($posts as $post)
                {
                    $id = $post->getAttribute("guid");
                    $fio = $post->getAttribute("fio");
                    $profile = $post->getAttribute("profile");
                    $specialityname = $post->getAttribute("specialityname");
                    $spacialityid = $post->getAttribute("spacialityid");
                    $spaciality = $post->getAttribute('spaciality');
                    $state = $post->getAttribute("state");
                    $division = $post->getAttribute("division");
                    $post_item = $this->add($id, $fio, $profile, $specialityname, $spacialityid, $state, $division);
                    $workdates = $post->getElementsByTagName("workdate");
                    foreach($workdates as $workdate)
                    {
                        $date = $workdate->getAttribute("date");
                        $timebegin = $workdate->getAttribute("timebegin");
                        $timeend = $workdate->getAttribute("timeend");
                        $place = $workdate->getAttribute("place");
                        $schedule = new workdate_class($date, $timebegin, $timeend, $place);
                        $tickets = $workdate->getElementsByTagName("ticket");
                        foreach($tickets as $ticket)
                        {
                            $id = $ticket->getAttribute("guid");
                            $time = $ticket->getAttribute("time");
                            $status = $ticket->getAttribute("status");
                            $schedule->tickets[] = new ticket_class($id, $time, $status);
                        }
                        $post_item->workdates[] = $schedule;
                    }
                }
            }
        }
    }

    class T_LPU_EXT extends T_LPU
    {
        public $posts;
        function LoadSchedule($server, $use_cache = true, $needposts)
        {
            global $auth, $dictionaries;
            $this->posts = new posts_class();
            $needread = true;
            if($use_cache || ($schedule_xml == ''))
            {
                $diff = MikronDateTime::DateDiff('s', strtotime($this->scheduleloadtime->value), time());
                $needread = $diff > 3600;
            }
            if($needread || !$use_cache)
            {
                try
                {
                    $dictionaries->getdata($server);
                    $speciality = $dictionaries->dic['speciality'];
                    array_unique($speciality);
                    $speciality = array_flip($speciality);
                    $schedule_xml = $this->posts->getdata($server, $speciality, constant('DATEBEGIN'), constant('DATEEND'), $needposts);
                    $this->schedule->value = $schedule_xml;
                    if($schedule_xml != false && $use_cache)
                    {
                        $this->scheduleloadtime->value = date('d-m-Y H:i:s');
                        $this->Save();
                    }
                }
                catch(Exception $ex)
                {
                
                }
            }
            $this->posts->parsexml($this->schedule->value);
        }
    }

    function getBottomBanners()
    {
        global $mikron;
        $items = $mikron->Queries->Query('T_BOTTOMBANNERS');
        $cnt = 0;
        ?><table cellspacing="0" cellpadding="8" width="100%"><tr><?php
        while($item = $items->fetch())
        {
            $string = $item->toString();
            if($cnt > 0)
            {
                ?><td class="leftborder"><?php echo $string; ?></td><?php
            }
            else
            {
                ?><td><?php echo $string; ?></td><?php
            }
            $cnt++;
        }
        ?></tr></table><?php
    }

    function getSearch()
    {
        $buf = "<form action=\"/search/\" method=\"GET\">
        <table width=\"100%\" cellspacing=\"0\" cellpadding=\"1\">
        <tr>
        <td width=\"1\" style=\"font-size: 8pt; color: #444; \">Поиск:</td>
        <td width=\"*\"><input size=\"12\" name=\"searchtext\" style=\"border: 1px solid #880; width: 100%; \"></td>
        <td width=\"1\"><input type=\"image\" src=\"/mikron/templates/main/images/pick.png\" value=\"Найти\"></td>
        </tr>
        </table>
        </form>";
        return $buf;
    }

    // Последние новости
    function getNews()
    {
        global $mikron;
        $buf = '';
        $items = $mikron->Queries->Query("T_NEWS", null, null, null, 8);
        ?><ul class="list1"><?php
        while($item = $items->fetch())
        {
            $id = $item->id;
            $anons = $item->anons->value;
            $text = $item->text->value;
            $url = $item->toURL();
            ?><li><a class="link2" href="$url"><?php echo $anons; ?></a></li><?php
        }
        ?></ul><?php
    }

    // Второстепенное вертикальное меню
    function getVerticalMenu()
    {
        global $mikron;
        $buf = "";
        $curpageurl = $mikron->Page->getCurrentPage();
        $curpage2 = quote_smart($curpageurl);
        $curpage = $mikron->Queries->Query("T_MENU", null, "`link`=$curpage2");
        if($curpage->count() < 1)
        {
            return null;
        }
        $curpage = $curpage->fetch();
        $curpage_id = (int)$curpage->id;

        if(is_null($curpage->parentmenu->value))
        {
            $parent_id = -1;
        }
        else
        {
            $parent_id = $curpage->parentmenu->value->id;
        }
        $items = $mikron->Queries->Query("T_MENU", null, new Criteria(Array(new Criterion('parentmenu',$curpage_id), new Criterion('parentmenu', $parent_id, CR_EQUAL, AO_OR))));
        ?><table cellpadding="0" cellspacing="0"><?php
        while($item = $items->fetch())
        {
            $url = $item->toURL();
            $title = $item->title->value;
            $group = $item->menugroup->value;
            if($group == 2)
            {
                if($curpageurl == $url)
                {
                    ?><tr>
                    <td><span class="listspan"><img src="/mikron/templates/webdoctor/images/bullet1.png"></span>
                    &nbsp;<?php echo $title; ?>
                    <br />&nbsp;</td></tr><?php
                }
                else
                {
                    ?><tr>
                    <td><div class="listspan">&nbsp;</div>
                    &nbsp;<a class="link3" href="<?php echo $url; ?>"><?php echo $title; ?></a>
                    <br />&nbsp;</td></tr><?php
                }
            }
        }
        ?></table><?php
    }

    // Главное меню
    function getMenu()
    {
        global $mikron;
        $buf = '';
        $items = $mikron->Queries->Query('T_MENU');
        $curpage = $mikron->Page->getCurrentPage();
        ?><ul id="mainnav"><?php
        while($item = $items->fetch())
        {
            $title = $item->title->value;
            $url = $item->toURL();
            $group = $item->menugroup->value;
            if($group == 1)
            {
                $pos = strpos($curpage, $url);
                $adrview = 0; // утопленная+ссылка
                if(!($pos===false)){$adrview = 2;} //поднятая+ссылка
                if($curpage == $url){$adrview = 1;} //поднятая+без ссылки
                if($url=="/")
                {
                    if(!($curpage == $url))
                    {
                        $adrview = 0; // утопленная+ссылка
                    }
                }
                // (адрес абсолютно совпадает) неактивное меню
                switch($adrview)
                {
                    case 0: // поднятая + ссылка
                        ?><DIV class="button22">
                        <DIV class="button21">
                        <DIV class="button23">
                            <table width="100%" height="100%" cellspacing="0" cellpadding="0" hight="52">
                            <tr>
                            <td class="activemenu">
                            <a href="<?php echo $url; ?>"><?php echo $title; ?></a>
                            </td>
                            </tr>
                            </table>
                        </DIV>
                        </DIV>
                        </DIV><?php
                        break;
                    case 1: // утопленная без ссылки
                        ?><DIV class="button12">
                        <DIV class="button11">
                        <DIV class="button13">
                            <table width="100%" height="100%" cellspacing="0" cellpadding="0" hight="52">
                            <tr>
                            <td class="unactivemenu">
                            <?php echo $title; ?>
                            </td>
                            </tr>
                            </table>
                        </DIV>
                        </DIV>
                        </DIV><?php
                        break;
                    case 2:  // утопленная + ссылка
                        ?><DIV class="button12">
                        <DIV class="button11">
                        <DIV class="button13">
                            <table width="100%" height="100%" cellspacing="0" cellpadding="0" hight="52">
                            <tr>
                            <td class="unactivemenu">
                            <a href="<?php echo $url; ?>"><?php echo $title; ?></a>
                            </td>
                            </tr>
                            </table>
                        </DIV>
                        </DIV>
                        </DIV><?php
                        break;
                }
            }
        }
        ?></ul><div class="mainnav_a_hover" style="position: absolute; left: -1000; ">&nbsp;</div><?php
    }

 ?>